"""json 格式文件操作"""
# -*- coding: utf-8 -*-
import re
import json
import os
import jsonpath

def read_json(json_path):
    """
    读取json
    """
    sep = os.path.sep
    with open(json_path.replace("\\", sep), "r", encoding="UTF-8") as f:
        return json.load(f, strict=False)


def set_json(json_data, json_path):
    """
    修改json
    """
    sep = os.path.sep
    with open(json_path.replace("\\", sep), 'w', encoding="UTF-8") as f:
        f.write(json.dumps(json_data,ensure_ascii=False))

def modify_cfg(json_path, exprs, new_values=None):
    '''
    修改json格式文件
    :param json_path: 文件路径
    :param exprs: jsonpath表达式
    :param new_values: 修改值
    :return: 修改之后的值
    '''
    with open(json_path, 'r', encoding='utf-8') as f:
        json_data = json.load(f)
    if new_values is None and not isinstance(exprs, list):
        if exprs == "$":
            return json_data
        result = jsonpath.jsonpath(json_data, exprs)
        if isinstance(result, bool):
            return result
        return result[0]
    old_value = ""
    new_value = ""
    if not isinstance(exprs, list):
        # 只修改一个的情况下
        exprs = [exprs]
        new_values = [new_values]
    for expr, new_value in zip(exprs, new_values):
        # 表达式匹配不到键，默认创建一个值
        if not jsonpath.jsonpath(json_data, expr):
            print(f'未匹配到键 {expr}，自动创建键值对')
            current_key_data = json_data
            for key in expr.split('.')[1:]:
                current_key_data = current_key_data.setdefault(key, {})
            current_key_data = new_value

        old_value = jsonpath.jsonpath(json_data, expr)[0]
        temp = expr.split('.')[1:]

        node = json_data
        for key in temp[:-1]:
            # 处理中间有列表的情况
            result = re.findall(r'\d+(?=\])', key)
            if result:
                key = key.split('[')[0]
            node = node.get(key, {})

            for x in result:
                node = node[int(x)]
        node[temp[-1]] = new_value
        new_value = jsonpath.jsonpath(json_data, expr)[0]
    print(f"旧值：{old_value} 新值：{new_value}")
    with open(json_path, 'w', encoding='utf-8') as f:
        f.write(json.dumps(json_data, ensure_ascii=False, indent=4))



if __name__ == '__main__':
    a = {
        "title": None,
        "tb_level": None,
        "tb_type": None
    }
    set_json(a, r'../static/json_data/screening_conditions.json')
